<?php


namespace Muyuxuan\redis;


trait Other
{
    private static $redis = null;
    public function __construct($config=[]){
        try {
            $defultconfig = require_once 'config.php';
            $newconfig = array_merge($defultconfig,$config);
            self::$redis = new \Redis();
            self::$redis->connect($newconfig['host'],$newconfig['port'],$newconfig['timeout']);
            if(!empty($newconfig['password'])){
                self::$redis->auth($newconfig['password']);
            }
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }
    /**
     * 设置redis
     * @param array $config
     */
    protected static function setRedis(array $config=[]){
        if(empty(self::$redis)){
            try{
                $defultconfig = require_once 'config.php';
                $newconfig = array_merge($defultconfig,$config);
                self::$redis = new \Redis();
                self::$redis->connect($newconfig['host'],$newconfig['port'],$newconfig['timeout']);
                if(!empty($newconfig['password'])){
                    self::$redis->auth($newconfig['password']);
                }
            }catch (\Exception $e){
                throw new \Exception($e->getMessage());
            }
        }
    }

    /**
     * 验证数组是否是索引数组
     * @param array $data
     * @return bool
     */
    public static function isNumArray(array $data){
        $key = array_keys($data,true);
        $bo = true;
        foreach ($key as $v){
            if(is_string($v)){
                $bo = false;
                break;
            }
        }
        return $bo;
    }

    /**
     * 删除键
     * @param string $key 键名
     * @return int
     * @throws \Exception
     */
    public static function delKey(string $key=''){
        self::setRedis();
        if(empty($key)){
            $key = self::$defaultKey;
        }
        return self::$redis->del($key);
    }

}